"""
肺结节CT场景处理器
"""

from medical_scenes.base.scene import MedicalScene
from medical_scenes.scenes.lung_nodule.models import (
    NoduleDetectionResult, 
    NoduleSegmentationResult, 
    NoduleClassificationResult,
    LungNoduleProcessingResult
)
from typing import List, Optional

class LungNoduleProcessor(MedicalScene):
    """肺结节CT场景处理器"""

    def __init__(self):
        super().__init__(
            scene_id="lung-nodule",
            name="肺结节CT",
            description="结节检测、分割与良恶性分类"
        )

        # 定义任务列表
        self.tasks = [
            {
                "id": "detection",
                "name": "肺结节检测",
                "description": "自动检测CT影像中的肺结节区域",
                "icon": "🔍"
            },
            {
                "id": "segmentation",
                "name": "肺结节分割",
                "description": "精确分割肺结节区域边界",
                "icon": "✂️"
            },
            {
                "id": "classification",
                "name": "肺结节良恶性分类",
                "description": "对检测到的肺结节进行良恶性分类诊断",
                "icon": "📊"
            }
        ]

    def get_tasks(self):
        """获取任务列表"""
        return self.tasks

    def detect_nodules(self, image_data: str, **kwargs) -> List[NoduleDetectionResult]:
        """
        执行肺结节检测任务
        
        Args:
            image_data: CT图像数据
            sensitivity: 检测敏感度
            
        Returns:
            List[NoduleDetectionResult]: 检测结果列表
        """
        # 简化实现，返回示例结果
        detections = [
            NoduleDetectionResult(
                id="nodule_1",
                center_x=100.0,
                center_y=150.0,
                center_z=50.0,
                diameter=8.5,
                volume=120.5,
                confidence=0.92
            )
        ]
        return detections

    def segment_nodules(
        self, image_data: str, **kwargs
    ) -> List[NoduleSegmentationResult]:
        """
        执行肺结节分割任务
        
        Args:
            image_data: CT图像数据
            nodule_ids: 要分割的结节ID列表，如果为None则分割所有检测到的结节
            
        Returns:
            List[NoduleSegmentationResult]: 分割结果列表
        """
        # 简化实现，返回示例结果
        segmentations = [
            NoduleSegmentationResult(
                nodule_id="nodule_1",
                mask="base64_encoded_mask_data",
                boundary_points=[[100, 150, 50], [105, 155, 50], [95, 145, 50]],
                confidence=0.88
            )
        ]
        return segmentations

    def classify_nodules(
        self, image_data: str, **kwargs
    ) -> List[NoduleClassificationResult]:
        """
        执行肺结节良恶性分类任务
        
        Args:
            image_data: CT图像数据
            nodule_ids: 要分类的结节ID列表，如果为None则分类所有检测到的结节
            
        Returns:
            List[NoduleClassificationResult]: 分类结果列表
        """
        # 简化实现，返回示例结果
        classifications = [
            NoduleClassificationResult(
                nodule_id="nodule_1",
                classification="benign",
                confidence=0.85,
                features={"size": 8.5, "texture": "smooth", "margin": "well_defined"}
            )
        ]
        return classifications

    def process(self, image_data, task_id: Optional[str] = None, **kwargs):
        """
        处理肺结节CT图像
        
        Args:
            image_data: CT图像数据
            task_id: 任务ID（detection, segmentation, classification），如果为None则执行所有任务
            **kwargs: 处理参数
            
        Returns:
            LungNoduleProcessingResult: 处理结果
        """
        # print(task_id)  # detection，证明是正确识别了
        # 根据任务ID执行相应的任务
        if task_id == "detection":
            detections = self.detect_nodules(image_data, **kwargs)
            result_dict = {"detections": detections}
            return LungNoduleProcessingResult(**result_dict)
        elif task_id == "segmentation":
            segmentations = self.segment_nodules(image_data, **kwargs)
            result_dict = {"segmentations": segmentations}
            return LungNoduleProcessingResult(**result_dict)
        elif task_id == "classification":
            classifications = self.classify_nodules(image_data, **kwargs)
            result_dict = {"classifications": classifications}
            return LungNoduleProcessingResult(**result_dict)
        else:
            # 执行所有任务
            detections = self.detect_nodules(image_data, **kwargs)
            segmentations = self.segment_nodules(image_data, **kwargs)
            classifications = self.classify_nodules(image_data, **kwargs)
            result_dict = {
                "detections": detections,
                "segmentations": segmentations,
                "classifications": classifications
            }
            return LungNoduleProcessingResult(**result_dict)
    def validate_input(self, image_data) -> bool:
        print("Base validate_input called")
        return True
